package com.hmall.trade.listener;


import com.hmall.common.constants.MqConstants;
import com.hmall.pay.domain.po.PayOrder;
import com.hmall.pay.service.IPayOrderService;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class OrderDelayMessageListener {

    private final IOrderService orderService;

    private final IPayOrderService payOrderService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.DELAY_ORDER_QUEUE_NAME),
            exchange = @Exchange(name = MqConstants.DELAY_EXCHANGE_NAME,delayed = "true"),
            key = MqConstants.DELAY_ORDER_KEY
    ))
    public void listenOrderDelayMessage(Long orderId){
        // 查询订单
        Order order = orderService.getById(orderId);
        // 判断订单是否已经支付
        if (order == null || order.getStatus() != 1){
            // 订单已经支付，或者订单不存在，则直接返回
             return;
        }
        // 订单未支付，查询支付流水状态
        PayOrder payOrder = payOrderService.lambdaQuery().eq(PayOrder::getBizOrderNo,orderId).one();

       if (payOrder.getStatus() == 3){
           orderService.markOrderPaySuccess(orderId);
       }else {
           //取消订单,将订单中已经扣除的库存重新加回来
           orderService.cancelOrder(orderId);
       }
    }
}
